package com.shlh.saas.controller;
import com.shlh.saas.common.Result;
import com.shlh.saas.common.UserContext;
import com.shlh.saas.entity.User;
import com.shlh.saas.entity.UserBalance;
import com.shlh.saas.entity.RechargeRecord;
import com.shlh.saas.entity.VipPackage;
import com.shlh.saas.entity.EmailPackage;
import com.shlh.saas.mapper.UserBalanceMapper;
import com.shlh.saas.service.RechargeRecordService;
import com.shlh.saas.service.UserService;
import com.shlh.saas.service.VipPackageService;
import com.shlh.saas.service.EmailPackageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 账户相关控制器
 */
@RestController
@RequestMapping("/account")
@Slf4j
public class AccountController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private RechargeRecordService rechargeRecordService;
    
    @Autowired
    private UserBalanceMapper userBalanceMapper;
    
    @Autowired
    private VipPackageService vipPackageService;
    
    @Autowired
    private EmailPackageService emailPackageService;
    
    // 缓存VIP套餐名称，避免频繁查询数据库
    private Map<Integer, String> vipLevelNameCache = new ConcurrentHashMap<>();
    
    // 缓存邮箱套餐名称，避免频繁查询数据库
    private Map<Integer, String> emailPackageNameCache = new ConcurrentHashMap<>();
    
    /**
     * 获取用户账户信息
     */
    @GetMapping("/info")
    public Result getAccountInfo() {
        try {
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return Result.error("未登录");
            }
            
            // 获取用户信息
            User user = userService.getById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 从UserBalance表获取余额和搜索配额
            UserBalance userBalance = userBalanceMapper.selectByUserId(userId);
            
            // 获取余额和搜索配额
            Map<String, Object> accountInfo = new HashMap<>();
            accountInfo.put("memberLevel", userBalance != null ? userBalance.getVipLevel() : 0);
            accountInfo.put("memberLevelText", getMemberLevelText(userBalance != null ? userBalance.getVipLevel() : 0));
            accountInfo.put("balance", userBalance != null ? userBalance.getCashBalance() : BigDecimal.ZERO);
            accountInfo.put("searchQuota", userBalance != null ? userBalance.getViewRecordsRemaining() : 0);
            
            // 添加邮箱套餐信息
            if (userBalance != null && userBalance.getEmailPackageLevel() != null) {
                accountInfo.put("emailPackageLevel", userBalance.getEmailPackageLevel());
                accountInfo.put("emailPackageName", getEmailPackageName(userBalance.getEmailPackageLevel()));
                accountInfo.put("emailSendRemaining", userBalance.getEmailSendRemaining());
            } else {
                accountInfo.put("emailPackageLevel", 0);
                accountInfo.put("emailPackageName", "未购买邮箱套餐");
                accountInfo.put("emailSendRemaining", 0);
            }
            
            return Result.success(accountInfo);
        } catch (Exception e) {
            log.error("获取账户信息失败", e);
            return Result.error("获取账户信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据会员等级获取对应的文本描述
     * @param vipLevel 会员等级
     * @return 会员等级文本描述
     */
    private String getMemberLevelText(Integer vipLevel) {
        // 首先从缓存中查找
        if (vipLevelNameCache.containsKey(vipLevel)) {
            return vipLevelNameCache.get(vipLevel);
        }
        
        try {
            // 获取所有有效的VIP套餐
            List<VipPackage> packages = vipPackageService.getAllValidPackages();
            
            // 查找对应等级的套餐名称
            for (VipPackage pkg : packages) {
                if (pkg.getLevel().equals(vipLevel)) {
                    // 缓存结果
                    vipLevelNameCache.put(vipLevel, pkg.getName());
                    return pkg.getName();
                }
            }
            
            // 如果没有找到，返回默认名称并缓存
            String defaultName = vipLevel == 0 ? "免费版" : "VIP" + vipLevel;
            vipLevelNameCache.put(vipLevel, defaultName);
            return defaultName;
        } catch (Exception e) {
            log.error("获取会员等级名称失败", e);
            // 发生异常时返回默认值
            return vipLevel == 0 ? "免费版" : "VIP" + vipLevel;
        }
    }
    
    /**
     * 根据邮箱套餐等级获取对应的文本描述
     * @param packageLevel 邮箱套餐等级
     * @return 邮箱套餐文本描述
     */
    private String getEmailPackageName(Integer packageLevel) {
        if (packageLevel == null || packageLevel == 0) {
            return "未购买邮箱套餐";
        }
        
        // 首先从缓存中查找
        if (emailPackageNameCache.containsKey(packageLevel)) {
            return emailPackageNameCache.get(packageLevel);
        }
        
        try {
            // 获取所有有效的邮箱套餐
            List<EmailPackage> packages = emailPackageService.getAllValidPackages();
            
            // 查找对应ID的套餐名称
            for (EmailPackage pkg : packages) {
                if (pkg.getId().intValue() == packageLevel) {
                    // 缓存结果
                    emailPackageNameCache.put(packageLevel, pkg.getName());
                    return pkg.getName();
                }
            }
            
            // 如果没有找到，返回默认名称并缓存
            String defaultName = "邮箱套餐" + packageLevel;
            emailPackageNameCache.put(packageLevel, defaultName);
            return defaultName;
        } catch (Exception e) {
            log.error("获取邮箱套餐名称失败", e);
            // 发生异常时返回默认值
            return "邮箱套餐" + packageLevel;
        }
    }
    
    /**
     * 获取交易记录
     */
    @GetMapping("/transactions")
    public Result getTransactions(@RequestParam(required = false) String type) {
        try {
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return Result.error("未登录");
            }
            
            // 获取用户信息
            User user = userService.getById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 使用用户手机号查询充值记录
            List<RechargeRecord> records = rechargeRecordService.getUserRecords(user.getPhone(), type);
            
            return Result.success(records);
        } catch (Exception e) {
            log.error("获取交易记录失败", e);
            return Result.error("获取交易记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 充值
     */
    @PostMapping("/recharge")
    @Transactional
    public Result recharge(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            // 第一步：获取手机号，这是最核心的用户标识
            String phone = null;
            
            // 从请求参数中获取手机号
            if (params.get("phone") != null) {
                phone = params.get("phone").toString();
                log.info("从请求参数中获取到手机号: {}", phone);
            } else {
                // 尝试从请求头中获取
                phone = request.getHeader("X-User-Phone");
                if (phone != null && !phone.isEmpty()) {
                    log.info("从请求头中获取到手机号: {}", phone);
                }
            }
            
            // 如果没有手机号，直接返回错误
            if (phone == null || phone.isEmpty()) {
                log.error("充值失败: 未找到有效的手机号");
                return Result.error("充值失败: 未找到有效的手机号");
            }
            
            // 第二步：提取参数
            Object amountObj = params.get("amount");
            if (amountObj == null) {
                return Result.error("充值金额不能为空");
            }
            
            BigDecimal amount;
            try {
                if (amountObj instanceof Number) {
                    amount = BigDecimal.valueOf(((Number) amountObj).doubleValue());
                } else {
                    amount = new BigDecimal(amountObj.toString());
                }
            } catch (Exception e) {
                return Result.error("充值金额格式错误");
            }
            
            // 校验金额
            if (amount.compareTo(BigDecimal.ZERO) <= 0) {
                return Result.error("充值金额必须大于0");
            }
            
            String description = params.get("description") != null ? params.get("description").toString() : "账户充值";
            
            // 第三步：查找用户 - 首先尝试通过手机号查找
            User user = userService.findByPhone(phone);
            if (user == null) {
                // 如果找不到用户，可以尝试使用getUserByPhone方法再次查找
                user = userService.getUserByPhone(phone);
                
                // 如果还是找不到，可以考虑自动创建用户
                if (user == null) {
                    log.info("通过手机号 {} 找不到用户，尝试自动创建", phone);
                    boolean created = userService.createUserByPhone(phone);
                    if (created) {
                        user = userService.findByPhone(phone);
                        log.info("成功创建用户: {}", user != null ? user.getId() : "创建失败");
                    } else {
                        log.error("用户自动创建失败，手机号: {}", phone);
                        return Result.error("用户不存在且无法自动创建");
                    }
                }
            }
            
            // 获取用户ID
            Long userId = user.getId();
            log.info("找到用户ID: {}, 手机号: {}", userId, phone);
            
            // 第四步：处理充值
            log.info("开始处理充值: userId={}, phone={}, amount={}", userId, phone, amount);
            
            // 获取用户余额
            UserBalance userBalance = userBalanceMapper.selectByUserId(userId);
            BigDecimal newBalance;
            
            if (userBalance == null) {
                // 创建新的余额记录
                userBalance = new UserBalance();
                userBalance.setUserId(userId);
                userBalance.setPhone(phone);
                userBalance.setCashBalance(amount);
                userBalance.setVipLevel(0);
                userBalance.setExportQuotaRemaining(0);
                userBalance.setViewRecordsRemaining(5);
                userBalance.setReverseLookupRemaining(0);
                userBalance.setEmailSendRemaining(0);
                
                userBalanceMapper.insert(userBalance);
                newBalance = amount;
            } else {
                // 更新余额
                newBalance = userBalance.getCashBalance().add(amount);
                userBalance.setCashBalance(newBalance);
                userBalanceMapper.updateById(userBalance);
            }
            
            // 创建充值记录
            boolean success = rechargeRecordService.createRecord(
                phone, 
                "CUSTOM", 
                amount, 
                newBalance, 
                description, 
                "SYSTEM", 
                null
            );
            
            if (success) {
                log.info("充值成功: userId={}, phone={}, amount={}", userId, phone, amount);
                return Result.success("充值成功");
            } else {
                log.error("充值失败: userId={}, phone={}, amount={}", userId, phone, amount);
                return Result.error("充值失败");
            }
        } catch (Exception e) {
            log.error("充值失败", e);
            return Result.error("充值失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取充值记录
     */
    @GetMapping("/recharge-records")
    public Result getRechargeRecords(
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String recharge_type,
            @RequestParam(required = false) Integer limit) {
        try {
            log.info("获取充值记录: phone={}, type={}, limit={}", phone, recharge_type, limit);
            
            // 如果没有提供手机号，尝试从当前登录用户获取
            if (phone == null || phone.isEmpty()) {
                Long userId = UserContext.getUserId();
                if (userId == null) {
                    return Result.error("未登录且未提供手机号");
                }
                
                User user = userService.getById(userId);
                if (user == null) {
                    return Result.error("用户不存在");
                }
                
                phone = user.getPhone();
                log.info("从当前登录用户获取手机号: {}", phone);
            }
            
            // 获取充值记录
            List<RechargeRecord> records = rechargeRecordService.getUserRecords(phone, recharge_type);
            
            // 如果设置了limit，限制返回数量
            if (limit != null && limit > 0 && records != null && records.size() > limit) {
                records = records.subList(0, limit);
            }
            
            return Result.success(records);
        } catch (Exception e) {
            log.error("获取充值记录失败", e);
            return Result.error("获取充值记录失败: " + e.getMessage());
        }
    }
    
}